<?php
declare (strict_types = 1);

namespace app\admin\controller\delivery\channel;

use app\common\model\delivery\Channel;
use app\common\model\delivery\CustomerGoods;
use think\annotation\route\Group;
use app\admin\traits\Actions;
use app\common\model\delivery\Customer as CustomerModel;
use app\common\model\delivery\ChannelGird;
use think\annotation\route\Route;

#[Group("delivery/channel-customer")]
class Customer extends ChannelBase
{
    use Actions{
        index as private _index;
        edit as private _edit;
        add as private _add;
        recyclebin as private _recyclebin;
        download as private _download;
    }

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new CustomerModel();
        $this->assign('gird',ChannelGird::where('channel_id',$this->channel->id)->column('gird_title','id'));
        $this->assign('settleType',Channel::SETTLE_TYPE);
    }

    //查看
    #[Route("GET,JSON","index")]
    public function index()
    {
        $this->relationField=["area"];
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if($this->request->post('selectpage')){
            return $this->selectpage();
        }
        $where = [];
        $where[] = ['channel_id','=',$this->channel->id];
        $where[] = ['customer_type','=',$this->request->get('type')];
        [$where, $order, $limit, $with] = $this->buildparams($where);
        $list = $this->model
            ->withJoin($with,'left')
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    //添加
    #[Route("GET,POST","add")]
    public function add()
    {
        if($this->request->isPost()){
            $this->parseData();
        }else{
            $this->assign('goods',$this->channel->goods);
        }
        return $this->_add();
    }

    #[Route('GET,JSON','download')]
    public function download()
    {
        $this->downloadController=Customer::class;
        return $this->_download();
    }

    //修改
    #[Route("GET,POST","edit")]
    public function edit()
    {
        $ids=$this->request->param("ids");
        $rows=CustomerModel::find($ids);
        if(!$rows || $rows->channel_id!=$this->channel->id){
            $this->error("参数错误");
        }
        if($this->request->isPost()){
            $this->parseData();
            return $this->_edit($rows);
        }else{
            $ids = $this->request->get('ids');
            $row = $this->model->find($ids);
            $row->area=[$row->province_id,$row->city_id,$row->area_id];
            $goods=$this->channel->goods;
            $price=CustomerGoods::where('customer_id',$ids)->column('price','spec_id');
            foreach ($goods as $k1=>$v1){
               foreach ($v1['spec'] as $k2=>$v2){
                   $goods[$k1]['spec'][$k2]['price']=$price[$v2['id']];
               }
            }
            $this->assign('row', $row);
            $this->assign('goods',$goods);
            return $this->fetch();
        }
    }

    //回收站
    #[Route("GET,POST,JSON","recyclebin")]
    public function recyclebin($action)
    {
        $this->recyclebinColumns=[
            "id"=>"ID",
            "name"=>"公司名称",
        ];
        $this->recyclebinColumnsType=[
            "id"=>"text",
            "name"=>"text",
        ];
        if($action=='list' && $this->request->isAjax()){
            $where = [];
            $where[] = ['channel_id','=',$this->channel->id];
            [$where, $order, $limit] = $this->buildparams($where);
            $list = $this->model
                ->onlyTrashed()
                ->where($where)
                ->order($order)
                ->paginate($limit);
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
        }
        return $this->_recyclebin($action);
    }

    private function parseData()
    {
        if($this->request->isPost()){
            $area=$this->request->post('area/a');
            $latlng=$this->request->post('latlng');
            if(!$latlng){
                $this->error('经纬度必填');
            }
            $latlng=explode(',',$latlng);
            $this->postParams=[
                'latitude'=>$latlng[0],
                'longitude'=>$latlng[1],
                'province_id'=>$area[0],
                'city_id'=>$area[1],
                'area_id'=>$area[2],
                'channel_id'=>$this->channel->id
            ];
            $this->callback=function ($row){
                $goods=$this->request->post('goods');
                $data=[];
                foreach($goods as $v){
                    $data[]=[
                        'customer_id'=>$row['id'],
                        'goods_id'=>$v['goods_id'],
                        'spec_id'=>$v['id'],
                        'price'=>$v['price']
                    ];
                }
                CustomerGoods::where('customer_id',$row['id'])->delete();
                (new CustomerGoods())->saveAll($data);
            };
        }
    }
}